package com.lw.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lw.yygh.cmn.listener.DictListener;
import com.lw.yygh.cmn.mapper.DictMapper;
import com.lw.yygh.cmn.service.DictService;
import com.lw.yygh.model.cmn.Dict;
import com.lw.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) { //前端实现递归逻辑（数据字典展示）
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        List<Dict> dicts = baseMapper.selectList( queryWrapper.eq( "parent_id", id ) );
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict:dicts){
            Long dictId = dict.getId();
            boolean isChild = isChildren( dictId );
            if (isChild){
                dict.setHasChildren( true );
            }else {
                dict.setHasChildren( false );
            }
        }
        return dicts;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = "dict";
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            //查询数据
            List<Dict> dicts = baseMapper.selectList( null );
            //dict--dictEeVo
            List<DictEeVo> dictEeVoList=new ArrayList<>();
            for (Dict dict:dicts){
                DictEeVo dictEeVo=new DictEeVo();
                BeanUtils.copyProperties( dict,dictEeVo );
                dictEeVoList.add( dictEeVo );
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class ).sheet("dict")
                    .doWrite( dictEeVoList );
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Autowired
    private DictListener dictListener;
    @Override
    //allEntries = true: 方法调用后清空所有缓存
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read( file.getInputStream(),DictEeVo.class ,dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id){
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq( "parent_id", id  );
        Integer count = baseMapper.selectCount( queryWrapper );
        return count>0?true:false;
    }
    //查询dictName
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查(查省市区)
        if (StringUtils.isEmpty( dictCode )){
            //直接根据value查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq( "id",value );
            Dict dict = baseMapper.selectOne( queryWrapper );
            return dict.getName();
        }else {//如果不为空，先根据dictCode查询dict对象的id值
            //再根据id值和value查出dict对象
            QueryWrapper<Dict> parentWrapper = new QueryWrapper<>();
            parentWrapper.eq( "dict_code",dictCode );
            Dict parentDict = baseMapper.selectOne( parentWrapper );
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq( "parent_id",parentDict.getId() ).eq( "value",value );
            Dict dict = baseMapper.selectOne( wrapper );
            return dict.getName();
        }
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应id 再根据id获取下级节点
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq( "dict_code",dictCode );
        Dict dict = baseMapper.selectOne( wrapper );
        List<Dict> dicts = this.findChildData( dict.getId() );
        return dicts;
    }
}
